package cn.edu.ncu.housinghub.service.impl;

import cn.edu.ncu.housinghub.constant.ErrorCodeConstant;
import cn.edu.ncu.housinghub.constant.SystemConstant;
import cn.edu.ncu.housinghub.entity.user.Agent;
import cn.edu.ncu.housinghub.entity.user.AgentVerification;
import cn.edu.ncu.housinghub.exception.BusinessException;
import cn.edu.ncu.housinghub.mapper.AgentMapper;
import cn.edu.ncu.housinghub.mapper.UserMapper;
import cn.edu.ncu.housinghub.service.AdminAgentService;
import cn.edu.ncu.housinghub.service.SystemNotificationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AdminAgentServiceImpl implements AdminAgentService {

    @Autowired
    private AgentMapper agentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SystemNotificationService systemNotificationService;

    // 添加依赖注入检查方法
    private void checkDependencies() {
        if (agentMapper == null) {
            log.error("❌ AgentMapper 依赖注入失败！");
            throw new BusinessException(ErrorCodeConstant.SYSTEM_ERROR, "AgentMapper 依赖注入失败");
        }
        if (userMapper == null) {
            log.error("❌ UserMapper 依赖注入失败！");
            throw new BusinessException(ErrorCodeConstant.SYSTEM_ERROR, "UserMapper 依赖注入失败");
        }
        if (systemNotificationService == null) {
            log.error("❌ SystemNotificationService 依赖注入失败！");
            throw new BusinessException(ErrorCodeConstant.SYSTEM_ERROR, "SystemNotificationService 依赖注入失败");
        }
        log.info("✅ 所有依赖注入检查通过");
    }

    @Override
    public List<AgentVerification> findAllApply() {
        try {
            // 检查依赖注入
            checkDependencies();

            List<AgentVerification> applications = agentMapper.selectAllApply();
            log.info("查询到 {} 条中介申请记录", applications != null ? applications.size() : 0);
            return applications;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("查询所有中介申请失败", e);
            throw new BusinessException(ErrorCodeConstant.SYSTEM_ERROR);
        }
    }

    @Override
    public List<AgentVerification> getAgentApply() {
        return findAllApply();
    }

    @Override
    public AgentVerification getAgentApplyById(Long userId) {
        try {
            // 查询未删除的申请记录
            AgentVerification result = agentMapper.selectApplyResult(userId);
            log.info("查询用户申请记录, userId: {}, 结果: {}", userId, result != null ? "找到记录" : "未找到记录");
            return result;
        } catch (Exception e) {
            log.error("根据用户ID查询中介申请失败, userId: {}", userId, e);
            throw new BusinessException(ErrorCodeConstant.SYSTEM_ERROR);
        }
    }

    @Override
    @Transactional
    public void approveAgentApply(Long userId) {
        try {
            // 根据userId查询申请信息
            AgentVerification agentVerification = agentMapper.selectApplyResult(userId);
            if (agentVerification == null) {
                throw new BusinessException(ErrorCodeConstant.AGENT_APPLY_NOT_FOUND);
            }

            // 检查申请状态
            if (!agentVerification.getVerifyStatus().equals(SystemConstant.AGENT_VERIFY_STATUS_PENDING.getIntegerValue())) {
                throw new BusinessException(ErrorCodeConstant.APPLY_HAS_BEEN_PROCESSED);
            }

            // 更新申请状态为通过
            agentMapper.updateApplyStatusById(agentVerification.getUserId(),
                SystemConstant.AGENT_VERIFY_STATUS_APPROVED.getIntegerValue(), null);

            // 更新用户角色为中介
            userMapper.updateRoleToAgent(agentVerification.getUserId());

            // 创建中介记录
            Agent agent = createAgentFromVerification(agentVerification);
            userMapper.addNewAgent(agent);

            // 发送系统通知
            sendApprovalNotification(agentVerification);

            log.info("中介申请审核通过成功, userId: {}, realName: {}",
                agentVerification.getUserId(), agentVerification.getRealName());

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("审核通过中介申请失败, userId: {}", userId, e);
            throw new BusinessException(ErrorCodeConstant.SYSTEM_ERROR);
        }
    }

    @Override
    @Transactional
    public void refuseAgentApply(Long userId) {
        try {
            // 根据userId查询申请信息
            AgentVerification agentVerification = agentMapper.selectApplyResult(userId);
            if (agentVerification == null) {
                throw new BusinessException(ErrorCodeConstant.AGENT_APPLY_NOT_FOUND);
            }

            // 检查申请状态
            if (!agentVerification.getVerifyStatus().equals(SystemConstant.AGENT_VERIFY_STATUS_PENDING.getIntegerValue())) {
                throw new BusinessException(ErrorCodeConstant.APPLY_HAS_BEEN_PROCESSED);
            }

            // 更新申请状态为拒绝
            agentMapper.updateApplyStatusById(agentVerification.getUserId(),
                SystemConstant.AGENT_VERIFY_STATUS_REJECTED.getIntegerValue(), agentVerification.getRefuseReason());

            // 发送系统通知
            sendRejectionNotification(agentVerification);

            log.info("中介申请审核拒绝成功, userId: {}, realName: {}, reason: {}",
                agentVerification.getUserId(), agentVerification.getRealName(), agentVerification.getRefuseReason());

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("审核拒绝中介申请失败, userId: {}", userId, e);
            throw new BusinessException(ErrorCodeConstant.SYSTEM_ERROR);
        }
    }

    @Override
    @Transactional
    public void modifyApplyStatusById(Long userId, Integer verifyStatus, String refuseReason) {
        try {
            // 查询申请信息
            AgentVerification agentVerification = agentMapper.selectApplyResult(userId);
            if (agentVerification == null) {
                throw new BusinessException(ErrorCodeConstant.AGENT_APPLY_NOT_FOUND, "中介申请不存在");
            }

            // 检查申请状态
            if (agentVerification.getVerifyStatus() != SystemConstant.AGENT_VERIFY_STATUS_PENDING.getIntegerValue()) {
                throw new BusinessException(ErrorCodeConstant.APPLY_HAS_BEEN_PROCESSED, "申请已被处理");
            }

            // 更新申请状态
            agentMapper.updateApplyStatusById(userId, verifyStatus, refuseReason);

            // 如果是通过申请，需要更新用户角色并创建中介记录
            if (verifyStatus.equals(SystemConstant.AGENT_VERIFY_STATUS_APPROVED.getIntegerValue())) {
                // 更新用户角色为中介
                userMapper.updateRoleToAgent(userId);

                // 创建中介记录
                Agent agent = createAgentFromVerification(agentVerification);
                userMapper.addNewAgent(agent);

                // 发送通过通知
                sendApprovalNotification(agentVerification);
            } else if (verifyStatus.equals(SystemConstant.AGENT_VERIFY_STATUS_REJECTED.getIntegerValue())) {
                // 发送拒绝通知
                agentVerification.setRefuseReason(refuseReason);
                sendRejectionNotification(agentVerification);
            }

            log.info("中介申请状态更新成功, userId: {}, verifyStatus: {}, refuseReason: {}",
                userId, verifyStatus, refuseReason);

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("更新中介申请状态失败, userId: {}, verifyStatus: {}", userId, verifyStatus, e);
            throw new BusinessException(ErrorCodeConstant.SYSTEM_ERROR, "更新申请状态失败");
        }
    }

    /**
     * 从中介申请信息创建中介记录
     */
    private Agent createAgentFromVerification(AgentVerification agentVerification) {
        Agent agent = new Agent();
        agent.setUserId(agentVerification.getUserId());
        agent.setAgentVerifyId(agentVerification.getAgentVerifyId());
        agent.setLicenseNo(agentVerification.getLicenseNo());
        agent.setLicensePicPath(agentVerification.getLicensePicPath());
        agent.setPhone(agentVerification.getPhone());
        agent.setCompanyName(agentVerification.getCompanyName());
        agent.setCompanyPosition(agentVerification.getCompanyPosition()); // 使用companyAddress字段
        agent.setRealName(agentVerification.getRealName());
        agent.setIdCard(agentVerification.getIdCard());
        agent.setEmail(agentVerification.getEmail());
        agent.setCity(agentVerification.getCity());
        agent.setWorkYears(agentVerification.getWorkYears());
        return agent;
    }

    /**
     * 发送审核通过通知
     */
    private void sendApprovalNotification(AgentVerification agentVerification) {
        try {
            systemNotificationService.sendAgentVerificationNotification(
                agentVerification.getUserId(),
                "approved",
                null
            );

            log.info("发送中介审核通过通知成功, userId: {}", agentVerification.getUserId());
        } catch (Exception e) {
            log.error("发送中介审核通过通知失败, userId: {}", agentVerification.getUserId(), e);
        }
    }

    /**
     * 发送审核拒绝通知
     */
    private void sendRejectionNotification(AgentVerification agentVerification) {
        try {
            systemNotificationService.sendAgentVerificationNotification(
                agentVerification.getUserId(),
                "rejected",
                agentVerification.getRefuseReason()
            );

            log.info("发送中介审核拒绝通知成功, userId: {}", agentVerification.getUserId());
        } catch (Exception e) {
            log.error("发送中介审核拒绝通知失败, userId: {}", agentVerification.getUserId(), e);
        }
    }
}
